import re
import hashlib

# 读取 static/index.html 文件
with open('static/index.html', 'r',encoding='utf8') as file:
    lines = file.readlines()

# 遍历每一行进行操作
for i, line in enumerate(lines):
    # 匹配 <script src="..."></script> 标签
    script_match = re.search(r'<script src="([^"]+\.js)"></script>', line)
    if script_match:
        file_path = script_match.group(1)
        # 检查文件是否存在
        try:
            # 计算文件的 MD5 值
            with open(file_path, 'rb') as file:
                md5_hash = hashlib.md5(file.read()).hexdigest()
            # 插入 <file>?<md5> 到相应位置
            line = line.replace(file_path, f'{file_path}?version={md5_hash}')
        except :
            continue
        
    # 匹配 <link rel="stylesheet" href="..."> 标签
    css_match = re.search(r'<link rel="stylesheet" type="text/css" href="([^"]+\.css)">', line)
    if css_match:
        file_path = css_match.group(1)
        # 检查文件是否存在
        try:
            # 计算文件的 MD5 值
            with open(file_path, 'rb') as file:
                md5_hash = hashlib.md5(file.read()).hexdigest()
            # 插入 <file>?<md5> 到相应位置
            line = line.replace(file_path, f'{file_path}?version={md5_hash}')
        except :
            continue
        
    # 将修改后的行写回列表
    lines[i] = line

# 将修改后的内容保存回 static/index.html 文件
with open('static/index.html', 'w',encoding='utf8') as file:
    file.writelines(lines)
